using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Media;
using Intuipic.Interop;

namespace Intuipic.Data
{
	/// <summary>
	/// Provides a concrete implementation of <see cref="InformationBase"/> that represents a drive on the system.
	/// </summary>
	public sealed class DriveInformation : InformationBase
	{
		private readonly DriveInfo _driveInfo;

		/// <summary>
		/// Creates an instance of <c>DriveInformation</c> representing the specified <see cref="DriveInfo"/>.
		/// </summary>
		public static DriveInformation GetDriveInformation(DriveInfo driveInfo)
		{
			Debug.Assert(driveInfo != null);

			string name = !driveInfo.IsReady || string.IsNullOrEmpty(driveInfo.VolumeLabel) ? driveInfo.Name : string.Format("{0} ({1})", driveInfo.VolumeLabel, driveInfo.Name);
			string path = driveInfo.Name;
			ImageSource icon = IconHelper.GetIcon(driveInfo.RootDirectory.Name, FileInfoAttributes.Directory, FileInfoFlags.Icon | FileInfoFlags.SmallIcon | FileInfoFlags.UseFileAttributes);

			return new DriveInformation(name, path, icon, driveInfo);
		}

		private DriveInformation(string name, string path, ImageSource icon, DriveInfo driveInfo)
			: base(name, path, icon, icon, null)
		{
			Debug.Assert(driveInfo != null);
			_driveInfo = driveInfo;
		}

		/// <summary>
		/// Loads the children of this drive informational item.
		/// </summary>
		protected override void LoadChildrenCore()
		{
			if ((_driveInfo.RootDirectory != null) && (_driveInfo.IsReady))
			{
				try
				{
					foreach (DirectoryInfo directoryInfo in _driveInfo.RootDirectory.GetDirectories())
					{
						Children.Add(new DirectoryInformation(this, directoryInfo));
					}
				}
				catch (UnauthorizedAccessException)
				{
					//swallow - no access to directory so we can't enumerate children
				}
			}
		}
	}
}
